#include "CroppingSettingsForm.h"
#include "ui_CroppingSettingsForm.h"
#include <QStyle>
#include <QDebug>
#include <QRegExpValidator>
#include <QStringList>

CroppingSettingsForm::CroppingSettingsForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CroppingSettingsForm),
    m_cropRect(0, 0, 100, 100),
    m_enableCrop(true)
{
    ui->setupUi(this);
    setAttribute(Qt::WA_StyledBackground, true);

    // 添加正则表达式验证
    // 验证X,Y格式：整数,整数
    QRegExp pointRegExp("^\\d+,\\d+$");
    ui->edit_LeftTop->setValidator(new QRegExpValidator(pointRegExp, this));
    ui->edit_RightTop->setValidator(new QRegExpValidator(pointRegExp, this));
    ui->edit_LeftBottom->setValidator(new QRegExpValidator(pointRegExp, this));
    ui->edit_RightBottom->setValidator(new QRegExpValidator(pointRegExp, this));

    // 初始化UI控件值
    updatePointEditsFromRect(m_cropRect);
    ui->checkBox_EnableCrop->setChecked(m_enableCrop);

    QPushButton *currentPushbutton = ui->button_Synchronize;
    currentPushbutton->setEnabled(false); // 默认禁用（灰色，不可点击）

    // 连接同步按钮的点击信号
    connect(ui->button_Synchronize, &QPushButton::clicked, this, &CroppingSettingsForm::on_synchronizeButton_clicked);
    // 连接确定按钮的点击信号
    connect(ui->button_Confirm, &QPushButton::clicked, this, &CroppingSettingsForm::on_confirmButton_clicked);
    // 连接启用裁剪复选框的信号
    connect(ui->checkBox_EnableCrop, &QCheckBox::stateChanged, this, [this](int state) {
        bool oldEnableCrop = m_enableCrop;
        m_enableCrop = (state == Qt::Checked);
        // 启用或禁用所有输入控件
        ui->edit_LeftTop->setEnabled(m_enableCrop);
        ui->edit_RightTop->setEnabled(m_enableCrop);
        ui->edit_LeftBottom->setEnabled(m_enableCrop);
        ui->edit_RightBottom->setEnabled(m_enableCrop);
        ui->button_Confirm->setEnabled(m_enableCrop);
        
        // 如果从启用变为禁用裁剪，发出信号通知父组件
        if (oldEnableCrop && !m_enableCrop) {
            // 发出空区域信号，触发图像还原
            emit cropRectChanged(QRect());
        }
    });
}

CroppingSettingsForm::~CroppingSettingsForm()
{
    delete ui;
}

void CroppingSettingsForm::updatePointEditsFromRect(const QRect& rect)
{
    // 根据矩形更新四个点的X,Y格式，确保形成矩形
    // 注意：QRect的right()和bottom()返回的是x+width-1和y+height-1，所以我们需要计算正确的右下角坐标
    int left = rect.left();
    int top = rect.top();
    int right = rect.left() + rect.width();
    int bottom = rect.top() + rect.height();
    
    QString leftTop = QString("%1,%2").arg(left).arg(top);
    QString rightTop = QString("%1,%2").arg(right).arg(top);
    QString leftBottom = QString("%1,%2").arg(left).arg(bottom);
    QString rightBottom = QString("%1,%2").arg(right).arg(bottom);
    
    // 断开信号连接，避免循环触发
    disconnect(ui->edit_LeftTop, &QLineEdit::editingFinished, this, nullptr);
    disconnect(ui->edit_RightTop, &QLineEdit::editingFinished, this, nullptr);
    disconnect(ui->edit_LeftBottom, &QLineEdit::editingFinished, this, nullptr);
    disconnect(ui->edit_RightBottom, &QLineEdit::editingFinished, this, nullptr);
    
    ui->edit_LeftTop->setText(leftTop);
    ui->edit_RightTop->setText(rightTop);
    ui->edit_LeftBottom->setText(leftBottom);
    ui->edit_RightBottom->setText(rightBottom);
    
    // 重新连接信号
    connect(ui->edit_LeftTop, &QLineEdit::editingFinished, this, &CroppingSettingsForm::onPointTextChanged);
    connect(ui->edit_RightTop, &QLineEdit::editingFinished, this, &CroppingSettingsForm::onPointTextChanged);
    connect(ui->edit_LeftBottom, &QLineEdit::editingFinished, this, &CroppingSettingsForm::onPointTextChanged);
    connect(ui->edit_RightBottom, &QLineEdit::editingFinished, this, &CroppingSettingsForm::onPointTextChanged);
}

void CroppingSettingsForm::setCropRect(const QRect& rect)
{
    m_cropRect = rect;
    
    // 如果是禁用裁剪状态（空区域），则不更新UI输入框
    // 这样当用户再次启用裁剪时，会保留之前的设置或显示完整图像区域
    if (!rect.isEmpty()) {
        updatePointEditsFromRect(m_cropRect);
    }
}

QRect CroppingSettingsForm::cropRect() const
{
    return m_cropRect;
}

bool CroppingSettingsForm::isCropEnabled() const
{
    return m_enableCrop;
}

void CroppingSettingsForm::on_synchronizeButton_clicked()
{
    // 同步按钮的处理逻辑
    // 这里可以添加同步UI值与实际裁剪区域的逻辑
}

bool CroppingSettingsForm::parsePoint(const QString& pointStr, int& x, int& y)
{
    QStringList parts = pointStr.split(",");
    if (parts.size() != 2) {
        return false;
    }
    
    bool xOk, yOk;
    x = parts[0].toInt(&xOk);
    y = parts[1].toInt(&yOk);
    
    return xOk && yOk;
}

void CroppingSettingsForm::onPointTextChanged()
{
    // 当任意一个点的文本改变时，更新其他点以保持矩形
    if (!m_enableCrop) {
        return;
    }
    
    // 获取当前焦点的输入框
    QLineEdit* focusedEdit = qobject_cast<QLineEdit*>(sender());
    if (!focusedEdit) {
        return;
    }
    
    // 解析当前所有点的坐标
    int leftTopX, leftTopY;
    int rightTopX, rightTopY;
    int leftBottomX, leftBottomY;
    int rightBottomX, rightBottomY;
    
    bool leftTopOk = parsePoint(ui->edit_LeftTop->text(), leftTopX, leftTopY);
    bool rightTopOk = parsePoint(ui->edit_RightTop->text(), rightTopX, rightTopY);
    bool leftBottomOk = parsePoint(ui->edit_LeftBottom->text(), leftBottomX, leftBottomY);
    bool rightBottomOk = parsePoint(ui->edit_RightBottom->text(), rightBottomX, rightBottomY);
    
    // 如果有任何一个点解析失败，直接返回
    if (!leftTopOk || !rightTopOk || !leftBottomOk || !rightBottomOk) {
        return;
    }

    // 根据焦点输入框更新其他点，保持矩形
    QRect rect;
    if (focusedEdit == ui->edit_LeftTop) {
        // 更新左上点，调整其他点
        rect = QRect(leftTopX, leftTopY, 
                    qMax(1, rightTopX - leftTopX),
                    qMax(1, leftBottomY - leftTopY));
    } else if (focusedEdit == ui->edit_RightTop) {
        // 更新右上点，调整其他点
        rect = QRect(leftTopX, rightTopY, 
                    qMax(1, rightTopX - leftTopX),
                    qMax(1, rightBottomY - rightTopY));
    } else if (focusedEdit == ui->edit_LeftBottom) {
        // 更新左下点，调整其他点
        rect = QRect(leftBottomX, leftTopY, 
                    qMax(1, rightBottomX - leftBottomX),
                    qMax(1, leftBottomY - leftTopY));
    } else if (focusedEdit == ui->edit_RightBottom) {
        // 更新右下点，调整其他点
        rect = QRect(leftTopX, leftTopY, 
                    qMax(1, rightBottomX - leftTopX),
                    qMax(1, rightBottomY - leftTopY));
    }

    // 更新所有点的坐标
    updatePointEditsFromRect(rect);
    m_cropRect=rect;
    emit cropRectChanged(m_cropRect);
}

void CroppingSettingsForm::on_confirmButton_clicked()
{
    // 如果未启用裁剪，直接返回
    if (!m_enableCrop) {
        return;
    }

    // 发出执行实际裁剪信号
    emit executeActualCrop();
}
